//
//  PlayHistoryViewController.swift
//  GhostWorld
//
//  Created by Kam on 2018/6/5.
//  Copyright © 2018 LKGood. All rights reserved.
//

import UIKit

private let audioCellIdentifier = "AudioTableCell"
private let noDataTableCellIdentifier = "NoDataTableCell"

class PlayHistoryViewController: BaseViewController {
  
  // MARK: - IBOutlets
  
  @IBOutlet weak var tableView: UITableView!
  
  // MARK: - Private vars
  
  private var playHistoryItems: [PlayHistoryItem]?
  
  // MARK: - Private methods
  
  private func prepareUI() {
    tableView.register(UINib(nibName: audioCellIdentifier, bundle: nil), forCellReuseIdentifier: audioCellIdentifier)
    tableView.register(UINib(nibName: noDataTableCellIdentifier, bundle: nil), forCellReuseIdentifier: noDataTableCellIdentifier)
    tableView.contentInset = UIEdgeInsets.init(top: 30, left: 0, bottom: 40, right: 0)
    tableView.scrollIndicatorInsets = tableView.contentInset
  }
  
  private func loadData() {
    playHistoryItems = PlayHistory.getAll()
    tableView.reloadData()
  }
  
  // MARK: - Public vars
  
  
  
  // MARK: - Lifecycle
  
  override func viewDidLoad() {
    super.viewDidLoad()
    
    prepareUI()
    loadData()
  }
  
  override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
  }
  
  // MARK: - IBActions
  
  @IBAction func close(_ sender: UIBarButtonItem) {
    if let navigationController = navigationController as? BaseNavigationController {
      navigationController.dismissDelegate?.dismiss(navigationController: navigationController, completion: nil)
    }
  }
  
  // MARK: - Public methods
  
}

extension PlayHistoryViewController: UITableViewDataSource {
  func numberOfSections(in tableView: UITableView) -> Int {
    return 1
  }
  
  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    if let count = playHistoryItems?.count, count > 0 {
      return count
    } else {
      return 1
    }
  }
  
  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let count = playHistoryItems?.count, count > 0 {
      // audio cell
      let cell = tableView.dequeueReusableCell(withIdentifier: audioCellIdentifier, for: indexPath) as! AudioTableCell
      let audio = playHistoryItems![indexPath.row].audio
      cell.prepare(audio: audio)
      return cell
    } else {
      // no data cell
      let cell = tableView.dequeueReusableCell(withIdentifier: noDataTableCellIdentifier, for: indexPath) as! NoDataTableCell
      cell.tipLabel.text = "没有播放历史"
      cell.selectionStyle = .none
      return cell
    }
  }
}

extension PlayHistoryViewController: UITableViewDelegate {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let count = playHistoryItems?.count, count > 0 {
      if let playHistoryItem = playHistoryItems?[indexPath.row] {
        // move cell to top
        tableView.deselectRow(at: indexPath, animated: true)
        playHistoryItems!.swapAt(indexPath.row, 0)
        tableView.moveRow(at: indexPath, to: IndexPath(row: 0, section: 0))
        tableView.scrollToRow(at: IndexPath(row: 0, section: 0), at: .top, animated: true)
        
        let audio = playHistoryItem.audio
        let album = playHistoryItem.album
        let relatedAudios = playHistoryItem.relatedAudios
//        let audios = playHistoryItems!.map { $0.audio }
        
        NowPlayingManager.shared.update (
          audioList: relatedAudios,
          audioListName: "播放历史",
          audioLsitType: .playHistory,
          audioListRefID: nil
        )
        NowPlayingManager.shared.play(album: album, audio: audio)
      } else {
        tableView.deselectRow(at: indexPath, animated: true)
      }
    } else {
      tableView.deselectRow(at: indexPath, animated: true)
    }
  }
  
  func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
    if let count = playHistoryItems?.count, count > 0 {
      return true
    } else {
      return false
    }
  }
  
  func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {
    if editingStyle == .delete {
      if let playHistoryItem = playHistoryItems?[indexPath.row] {
        do {
          try PlayHistory.remove (
            albumID: Int(playHistoryItem.album.id),
            audioID: Int(playHistoryItem.audio.id)
          )
          playHistoryItems?.remove(at: indexPath.row)
          if let count = playHistoryItems?.count, count > 0 {
            tableView.deleteRows(at: [indexPath], with: .fade)
          } else {
            tableView.reloadRows(at: [IndexPath(row: 0, section: 0)], with: .automatic)
          }
        } catch { }
      }
    }
  }
  
  func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    if let count = playHistoryItems?.count, count > 0 {
      return 60
    } else {
      return 44
    }
  }
}
